// API接口测试工具
import { 
  authApi, 
  orderApi, 
  serviceApi, 
  merchantApi, 
  userApi, 
  addressApi, 
  searchApi, 
  dashboardApi, 
  uploadApi 
} from '@/services/api'

/**
 * API接口测试类
 */
export class ApiTester {
  constructor() {
    this.results = []
    this.isRunning = false
  }

  /**
   * 记录测试结果
   */
  log(module, method, status, message, data = null) {
    const result = {
      timestamp: new Date().toISOString(),
      module,
      method,
      status, // 'success' | 'error' | 'warning'
      message,
      data
    }
    this.results.push(result)
    console.log(`[API测试] ${module}.${method}: ${status} - ${message}`, data)
  }

  /**
   * 测试认证模块
   */
  async testAuthModule() {
    console.log('🔐 开始测试认证模块...')
    
    try {
      // 测试用户注册
      const registerData = {
        username: `testuser_${Date.now()}`,
        email: `test_${Date.now()}@example.com`,
        password: '123456',
        mobile: '13800138000'
      }
      
      try {
        await authApi.register(registerData)
        this.log('authApi', 'register', 'success', '用户注册成功')
      } catch (error) {
        this.log('authApi', 'register', 'error', '用户注册失败', error.message)
      }

      // 测试用户登录
      try {
        const loginResponse = await authApi.login({
          username: 'testuser',
          password: '123456'
        })
        this.log('authApi', 'login', 'success', '用户登录成功', loginResponse.data)
        
        // 测试获取用户信息
        try {
          const userInfo = await authApi.getUserInfo()
          this.log('authApi', 'getUserInfo', 'success', '获取用户信息成功', userInfo.data)
        } catch (error) {
          this.log('authApi', 'getUserInfo', 'error', '获取用户信息失败', error.message)
        }
        
      } catch (error) {
        this.log('authApi', 'login', 'error', '用户登录失败', error.message)
      }

    } catch (error) {
      this.log('authApi', 'module', 'error', '认证模块测试异常', error.message)
    }
  }

  /**
   * 测试服务模块
   */
  async testServiceModule() {
    console.log('🛍️ 开始测试服务模块...')
    
    try {
      // 测试获取服务分类
      try {
        const categories = await serviceApi.getServiceCategories()
        this.log('serviceApi', 'getServiceCategories', 'success', '获取服务分类成功', categories.data)
      } catch (error) {
        this.log('serviceApi', 'getServiceCategories', 'error', '获取服务分类失败', error.message)
      }

      // 测试获取服务列表
      try {
        const services = await serviceApi.getServiceList({ page: 0, size: 10 })
        this.log('serviceApi', 'getServiceList', 'success', '获取服务列表成功', services.data)
      } catch (error) {
        this.log('serviceApi', 'getServiceList', 'error', '获取服务列表失败', error.message)
      }

      // 测试获取推荐服务
      try {
        const recommended = await serviceApi.getRecommendedServices({ limit: 5 })
        this.log('serviceApi', 'getRecommendedServices', 'success', '获取推荐服务成功', recommended.data)
      } catch (error) {
        this.log('serviceApi', 'getRecommendedServices', 'error', '获取推荐服务失败', error.message)
      }

    } catch (error) {
      this.log('serviceApi', 'module', 'error', '服务模块测试异常', error.message)
    }
  }

  /**
   * 测试商家模块
   */
  async testMerchantModule() {
    console.log('🏪 开始测试商家模块...')
    
    try {
      // 测试获取商家列表
      try {
        const merchants = await merchantApi.getMerchantList({ page: 0, size: 10 })
        this.log('merchantApi', 'getMerchantList', 'success', '获取商家列表成功', merchants.data)
      } catch (error) {
        this.log('merchantApi', 'getMerchantList', 'error', '获取商家列表失败', error.message)
      }

      // 测试获取热门商家
      try {
        const popular = await merchantApi.getPopularMerchants({ limit: 5 })
        this.log('merchantApi', 'getPopularMerchants', 'success', '获取热门商家成功', popular.data)
      } catch (error) {
        this.log('merchantApi', 'getPopularMerchants', 'error', '获取热门商家失败', error.message)
      }

    } catch (error) {
      this.log('merchantApi', 'module', 'error', '商家模块测试异常', error.message)
    }
  }

  /**
   * 测试搜索模块
   */
  async testSearchModule() {
    console.log('🔍 开始测试搜索模块...')
    
    try {
      // 测试综合搜索
      try {
        const searchResult = await searchApi.search({ keyword: '洗衣', page: 0, size: 10 })
        this.log('searchApi', 'search', 'success', '综合搜索成功', searchResult.data)
      } catch (error) {
        this.log('searchApi', 'search', 'error', '综合搜索失败', error.message)
      }

      // 测试获取推荐内容
      try {
        const recommendations = await searchApi.getRecommendations()
        this.log('searchApi', 'getRecommendations', 'success', '获取推荐内容成功', recommendations.data)
      } catch (error) {
        this.log('searchApi', 'getRecommendations', 'error', '获取推荐内容失败', error.message)
      }

    } catch (error) {
      this.log('searchApi', 'module', 'error', '搜索模块测试异常', error.message)
    }
  }

  /**
   * 运行所有测试
   */
  async runAllTests() {
    if (this.isRunning) {
      console.warn('测试正在运行中...')
      return
    }

    this.isRunning = true
    this.results = []
    
    console.log('🚀 开始API接口测试...')
    console.log('📋 测试目标: Spring Boot后端 (http://localhost:8080/api)')
    
    try {
      await this.testAuthModule()
      await this.testServiceModule()
      await this.testMerchantModule()
      await this.testSearchModule()
      
      console.log('✅ API接口测试完成!')
      this.printSummary()
      
    } catch (error) {
      console.error('❌ API接口测试异常:', error)
    } finally {
      this.isRunning = false
    }
    
    return this.results
  }

  /**
   * 打印测试摘要
   */
  printSummary() {
    const total = this.results.length
    const success = this.results.filter(r => r.status === 'success').length
    const error = this.results.filter(r => r.status === 'error').length
    const warning = this.results.filter(r => r.status === 'warning').length
    
    console.log('\n📊 测试摘要:')
    console.log(`总测试数: ${total}`)
    console.log(`✅ 成功: ${success}`)
    console.log(`❌ 失败: ${error}`)
    console.log(`⚠️ 警告: ${warning}`)
    console.log(`成功率: ${total > 0 ? ((success / total) * 100).toFixed(1) : 0}%`)
    
    if (error > 0) {
      console.log('\n❌ 失败的接口:')
      this.results
        .filter(r => r.status === 'error')
        .forEach(r => console.log(`  - ${r.module}.${r.method}: ${r.message}`))
    }
  }

  /**
   * 获取测试结果
   */
  getResults() {
    return this.results
  }

  /**
   * 清除测试结果
   */
  clearResults() {
    this.results = []
  }
}

// 创建全局测试实例
export const apiTester = new ApiTester()

// 导出便捷方法
export const runApiTests = () => apiTester.runAllTests()
export const getTestResults = () => apiTester.getResults()
export const clearTestResults = () => apiTester.clearResults()

// 开发环境下自动暴露到window对象
if (import.meta.env.DEV) {
  window.apiTester = apiTester
  window.runApiTests = runApiTests
  console.log('🔧 开发模式: API测试工具已加载')
  console.log('💡 使用方法: window.runApiTests() 或 apiTester.runAllTests()')
}
